package main.parser;

import java.util.List;
import main.flow.Flow;

public class FlowParser
{
	private String[] params;
	private String flowId;
	private List<Flow> flows;
	private Float time;
	
	public FlowParser(List<Flow> _flows, Float _time)
	{
		flows = _flows;
		time = _time;
	}
	
	public boolean parse(String line)
	{
		params = line.trim().split("\\s");
		if (!checkHeader()) return false;
		
		flowId = params[1] + " " + params[2] + " " + params[3];		
		int params = parseValues();
		
		return (params > 0);
	}
	
	private boolean checkHeader()
	{		
		if (!params[0].equals("flowID")) return false;
		if (params.length < 6) return false;		
		return true;
	}
	
	private int parseValues()
	{
		String name;
		int value;
		int parameters = 0;
		
		for (int i=4; i<params.length; i+=2)
		{
			try
			{
				name = params[i];
				value = Integer.parseInt(params[i+1]);
				
				parameters++;
				addValue(name, value);
			}
			
			catch (NumberFormatException e)
			{
			}
		}
		
		return parameters;
	}
	
	private void addValue(String name, int value)
	{		
		for (Flow flow : flows)
		{
			if ((flow.getId().equals(flowId)) && (flow.getName().equals(name)))
			{
				flow.addValue(time, value);
				return;
			}
		}
		
		Flow flow = new Flow();
		flow.setId(flowId);
		flow.setName(name);
		flow.addValue(time, value);
		flows.add(flow);
	}
}
